<template>
  <div class="container fade-in">
    <div class="header">
      <div class="breadcrumb">
        <router-link to="/coupons" class="breadcrumb-link">优惠券管理</router-link>
        <span class="breadcrumb-separator">></span>
        <span class="breadcrumb-current">{{ isEdit ? '编辑模板' : '创建模板' }}</span>
      </div>
      <div class="actions">
        <button class="btn secondary" @click="$router.back()">
          <span class="icon">←</span>
          返回
        </button>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else class="content">
      <div class="card slide-up">
        <div class="card-header">
          <h3 class="section-title">{{ isEdit ? '编辑优惠券模板' : '创建优惠券模板' }}</h3>
        </div>

        <form @submit.prevent="submitForm" class="form">
          <div class="form-grid">
            <!-- 基本信息 -->
            <div class="form-section">
              <h4 class="section-subtitle">基本信息</h4>
              
              <div class="field">
                <label class="required">模板名称</label>
                <input 
                  v-model="form.name" 
                  class="input" 
                  placeholder="请输入优惠券模板名称"
                  required
                  maxlength="50"
                />
                <div class="field-hint">建议使用简洁明了的名称，便于管理和识别</div>
              </div>

              <div class="field">
                <label>描述</label>
                <textarea 
                  v-model="form.description" 
                  class="input textarea" 
                  placeholder="请输入优惠券描述（可选）"
                  rows="3"
                  maxlength="200"
                ></textarea>
                <div class="field-hint">描述信息将显示给用户，建议说明使用条件和优惠内容</div>
              </div>

              <div class="field">
                <label class="required">优惠券类型</label>
                <div class="radio-group">
                  <label class="radio-item">
                    <input 
                      type="radio" 
                      v-model="form.couponType" 
                      :value="CouponType.REDUCTION"
                      @change="onCouponTypeChange"
                    />
                    <span class="radio-label">满减券</span>
                    <span class="radio-desc">满足条件减免固定金额</span>
                  </label>
                  <label class="radio-item">
                    <input 
                      type="radio" 
                      v-model="form.couponType" 
                      :value="CouponType.DISCOUNT"
                      @change="onCouponTypeChange"
                    />
                    <span class="radio-label">折扣券</span>
                    <span class="radio-desc">按比例折扣优惠</span>
                  </label>
                </div>
              </div>
            </div>

            <!-- 优惠设置 -->
            <div class="form-section">
              <h4 class="section-subtitle">优惠设置</h4>

              <div v-if="form.couponType === CouponType.REDUCTION" class="field">
                <label class="required">减免金额</label>
                <div class="input-group">
                  <span class="input-prefix">¥</span>
                  <input 
                    v-model.number="discountAmountYuan" 
                    type="number" 
                    class="input" 
                    placeholder="0.00"
                    min="0.01"
                    step="0.01"
                    required
                  />
                </div>
                <div class="field-hint">用户使用优惠券时减免的金额</div>
              </div>

              <div v-if="form.couponType === CouponType.DISCOUNT" class="field">
                <label class="required">折扣比例</label>
                <div class="input-group">
                  <input 
                    v-model.number="form.discount" 
                    type="number" 
                    class="input" 
                    placeholder="0.8"
                    min="0.1"
                    max="0.99"
                    step="0.01"
                    required
                  />
                  <span class="input-suffix">折</span>
                </div>
                <div class="field-hint">例如：0.8 表示 8 折优惠</div>
              </div>

              <div class="field">
                <label>使用门槛</label>
                <div class="input-group">
                  <span class="input-prefix">满</span>
                  <input 
                    v-model.number="usageThresholdYuan" 
                    type="number" 
                    class="input" 
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                  />
                  <span class="input-suffix">元可用</span>
                </div>
                <div class="field-hint">留空或填0表示无门槛使用</div>
              </div>

              <div class="field">
                <label class="required">费用承担方</label>
                <div class="radio-group">
                  <label class="radio-item">
                    <input 
                      type="radio" 
                      v-model="form.schemeType" 
                      :value="1"
                    />
                    <span class="radio-label">消费者承担</span>
                    <span class="radio-desc">服务费由消费者支付</span>
                  </label>
                  <label class="radio-item">
                    <input 
                      type="radio" 
                      v-model="form.schemeType" 
                      :value="2"
                    />
                    <span class="radio-label">商家承担</span>
                    <span class="radio-desc">服务费由商家支付</span>
                  </label>
                </div>
              </div>
            </div>

            <!-- 库存和有效期 -->
            <div class="form-section">
              <h4 class="section-subtitle">库存和有效期</h4>

              <div class="field">
                <label class="required">初始库存</label>
                <input 
                  v-model.number="form.inventory" 
                  type="number" 
                  class="input" 
                  placeholder="100"
                  min="1"
                  required
                />
                <div class="field-hint">优惠券的初始发放数量</div>
              </div>

              <div class="field">
                <label class="required">有效期</label>
                <div class="input-group">
                  <input 
                    v-model.number="form.validityPeriod" 
                    type="number" 
                    class="input" 
                    placeholder="30"
                    min="1"
                    max="365"
                    required
                  />
                  <span class="input-suffix">天</span>
                </div>
                <div class="field-hint">用户领取后的有效使用天数</div>
              </div>

              <div class="field">
                <label>状态</label>
                <div class="switch-group">
                  <label class="switch">
                    <input type="checkbox" v-model="form.isActive" />
                    <span class="switch-slider"></span>
                    <span class="switch-label">{{ form.isActive ? '启用' : '禁用' }}</span>
                  </label>
                </div>
                <div class="field-hint">禁用后用户无法领取此优惠券</div>
              </div>
            </div>
          </div>

          <!-- 预览区域 -->
          <div class="preview-section">
            <h4 class="section-subtitle">优惠券预览</h4>
            <div class="coupon-preview">
              <div class="coupon-card" :class="getCouponTypeClass()">
                <div class="coupon-header">
                  <div class="coupon-value">
                    <span v-if="form.couponType === CouponType.REDUCTION" class="value">
                      ¥{{ (discountAmountYuan || 0).toFixed(2) }}
                    </span>
                    <span v-else-if="form.couponType === CouponType.DISCOUNT" class="value">
                      {{ ((form.discount || 0) * 10).toFixed(1) }}折
                    </span>
                    <span v-else class="value">-</span>
                  </div>
                  <div class="coupon-type">
                    {{ getCouponTypeText(form.couponType) }}
                  </div>
                </div>
                <div class="coupon-body">
                  <div class="coupon-name">{{ form.name || '优惠券名称' }}</div>
                  <div class="coupon-condition">
                    {{ usageThresholdYuan > 0 ? `满¥${usageThresholdYuan.toFixed(2)}可用` : '无门槛使用' }}
                  </div>
                  <div class="coupon-validity">
                    有效期：{{ form.validityPeriod || 0 }}天
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 表单操作 -->
          <div class="form-actions">
            <button type="button" class="btn secondary" @click="$router.back()">
              取消
            </button>
            <button type="submit" class="btn primary" :disabled="submitting">
              {{ submitting ? '保存中...' : (isEdit ? '保存修改' : '创建模板') }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  CouponService, 
  type CouponTemplateCreateRequest,
  type CouponTemplateUpdateRequest,
  CouponType,
  getCouponTypeText
} from '../services/coupon'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)

// 表单数据
const form = reactive<CouponTemplateCreateRequest & { id?: string }>({
  name: '',
  description: '',
  couponType: CouponType.REDUCTION,
  discountAmount: 0,
  discount: 0.8,
  useThresholdAmount: 0,
  schemeType: 1,
  inventory: 100,
  validityPeriod: 30,
  isActive: true,
  platformServiceFeeRate: 0,
  receiveStartTime: new Date().toISOString(),
  receiveEndTime: new Date().toISOString(),
  validityType: 1,
  validityStartTime: new Date().toISOString(),
  validityEndTime: new Date().toISOString(),
  total: 0,
  maxIssuePerUser: 1,
  merchantId: '',
  enableStatus: 1,
  effectiveDelayType: 0,
  useFrequencyType: 1,
  useFrequencyLimit: 1
})

// 计算属性
const isEdit = computed(() => !!route.params.id)

const discountAmountYuan = computed({
  get: () => form.discountAmount ? form.discountAmount / 100 : 0,
  set: (value: number) => {
    form.discountAmount = Math.round(value * 100)
  }
})

const usageThresholdYuan = computed(() => form.useThresholdAmount ? form.useThresholdAmount / 100 : 0)


// 生命周期
onMounted(() => {
  if (isEdit.value) {
    loadTemplateDetail(route.params.id as string)
  }
})

// 监听优惠券类型变化
watch(() => form.couponType, (newType) => {
  if (newType === CouponType.REDUCTION) {
    form.discount = 0
  } else if (newType === CouponType.DISCOUNT) {
    form.discountAmount = 0
  }
})

// 方法
async function loadTemplateDetail(id: string) {
  loading.value = true
  try {
    const result = await CouponService.getTemplateDetail(id)
    if (result.code === 0 && result.data) {
      const template = result.data
      Object.assign(form, {
        id: template.id,
        name: template.name,
        description: template.description,
        couponType: template.couponType,
        discountAmount: template.discountAmount,
        discount: template.discount,
        useThresholdAmount: template.useThresholdAmount,
        schemeType: template.schemeType,
        inventory: template.inventory,
        validityPeriod: template.validityPeriod,
        isActive: template.isActive
      })
    } else {
      alert('加载模板详情失败：' + result.message)
      router.back()
    }
  } catch (error) {
    console.error('加载模板详情出错:', error)
    alert('加载失败，请稍后重试')
    router.back()
  } finally {
    loading.value = false
  }
}

async function submitForm() {
  if (!validateForm()) {
    return
  }

  submitting.value = true
  try {
    let result
    if (isEdit.value) {
      const updateData: CouponTemplateUpdateRequest = {
        id: form.id!,
        name: form.name,
        description: form.description,
        couponType: form.couponType,
        discountAmount: form.couponType === CouponType.REDUCTION ? form.discountAmount : 0,
        discount: form.couponType === CouponType.DISCOUNT ? form.discount : 0,
        useThresholdAmount: form.useThresholdAmount,
        schemeType: form.schemeType,
        validityPeriod: form.validityPeriod,
        isActive: form.isActive,
        platformServiceFeeRate: form.platformServiceFeeRate,
        receiveStartTime: form.receiveStartTime,
        receiveEndTime: form.receiveEndTime,
        validityType: form.validityType,
        validityStartTime: form.validityStartTime,
        validityEndTime: form.validityEndTime,
        total: form.total,
        maxIssuePerUser: form.maxIssuePerUser,
        merchantId: form.merchantId,
        enableStatus: form.enableStatus,
        effectiveDelayType: form.effectiveDelayType,
        useFrequencyType: form.useFrequencyType,
        useFrequencyLimit: form.useFrequencyLimit
      }
      result = await CouponService.updateTemplate(updateData)
    } else {
      const createData: CouponTemplateCreateRequest = {
        name: form.name,
        description: form.description,
        couponType: form.couponType,
        discountAmount: form.couponType === CouponType.REDUCTION ? form.discountAmount : 0,
        discount: form.couponType === CouponType.DISCOUNT ? form.discount : 0,
        useThresholdAmount: form.useThresholdAmount,
        schemeType: form.schemeType,
        inventory: form.inventory,
        validityPeriod: form.validityPeriod,
        isActive: form.isActive,
        platformServiceFeeRate: form.platformServiceFeeRate,
        receiveStartTime: form.receiveStartTime,
        receiveEndTime: form.receiveEndTime,
        validityType: form.validityType,
        validityStartTime: form.validityStartTime,
        validityEndTime: form.validityEndTime,
        total: form.total,
        maxIssuePerUser: form.maxIssuePerUser,
        merchantId: form.merchantId,
        enableStatus: form.enableStatus,
        effectiveDelayType: form.effectiveDelayType,
        useFrequencyType: form.useFrequencyType,
        useFrequencyLimit: form.useFrequencyLimit
      }
      result = await CouponService.createTemplate(createData)
    }

    if (result.code === 0) {
      alert(isEdit.value ? '修改成功' : '创建成功')
      router.push('/coupons')
    } else {
      alert((isEdit.value ? '修改失败：' : '创建失败：') + result.message)
    }
  } catch (error) {
    console.error('提交表单出错:', error)
    alert('操作失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

function validateForm(): boolean {
  if (!form.name.trim()) {
    alert('请输入模板名称')
    return false
  }

  if (form.couponType === CouponType.REDUCTION) {
    if (!form.discountAmount || form.discountAmount <= 0) {
      alert('请输入有效的减免金额')
      return false
    }
  } else if (form.couponType === CouponType.DISCOUNT) {
    if (!form.discount || form.discount <= 0 || form.discount >= 1) {
      alert('请输入有效的折扣比例（0.1-0.99）')
      return false
    }
  }

  if (!isEdit.value && (!form.inventory || form.inventory <= 0)) {
    alert('请输入有效的初始库存')
    return false
  }

  if (!form.validityPeriod || form.validityPeriod <= 0) {
    alert('请输入有效的有效期天数')
    return false
  }

  return true
}

function onCouponTypeChange() {
  // 切换类型时重置相关字段
  if (form.couponType === CouponType.REDUCTION) {
    form.discount = 0
  } else if (form.couponType === CouponType.DISCOUNT) {
    form.discountAmount = 0
  }
}

function getCouponTypeClass(): string {
  return form.couponType === CouponType.REDUCTION ? 'reduction' : 'discount'
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  gap: var(--space-6);
  padding: var(--space-4);
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-4);
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  font-size: var(--text-sm);
}

.breadcrumb-link {
  color: var(--primary);
  text-decoration: none;
}

.breadcrumb-link:hover {
  text-decoration: underline;
}

.breadcrumb-separator {
  color: var(--text-muted);
}

.breadcrumb-current {
  color: var(--text);
  font-weight: 500;
}

.actions {
  display: flex;
  gap: var(--space-3);
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: var(--space-2);
  padding: var(--space-3) var(--space-4);
  border: none;
  border-radius: var(--radius);
  font-size: var(--text-sm);
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
}

.btn.primary {
  background: var(--primary);
  color: white;
}

.btn.primary:hover:not(:disabled) {
  background: var(--primary-600);
  transform: translateY(-1px);
}

.btn.secondary {
  background: var(--bg-secondary);
  color: var(--text-secondary);
  border: 1px solid var(--border);
}

.btn.secondary:hover {
  background: var(--card-hover);
  color: var(--text);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-12);
  text-align: center;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top: 3px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--space-4);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.card-header {
  margin-bottom: var(--space-6);
}

.section-title {
  margin: 0;
  font-size: var(--text-xl);
  font-weight: 600;
  color: var(--text);
}

.form {
  display: flex;
  flex-direction: column;
  gap: var(--space-8);
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: var(--space-8);
}

.form-section {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.section-subtitle {
  margin: 0 0 var(--space-4) 0;
  font-size: var(--text-lg);
  font-weight: 600;
  color: var(--text-secondary);
  border-bottom: 2px solid var(--primary);
  padding-bottom: var(--space-2);
}

.field {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.field label {
  font-size: var(--text-sm);
  font-weight: 500;
  color: var(--text-secondary);
}

.field label.required::after {
  content: ' *';
  color: var(--danger);
}

.input {
  padding: var(--space-3);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  font-size: var(--text-sm);
  transition: all 0.2s ease;
  background: var(--card-bg);
}

.input:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px var(--primary-bg);
}

.textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.input-group {
  display: flex;
  align-items: center;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  background: var(--card-bg);
  transition: border-color 0.2s ease;
}

.input-group:focus-within {
  border-color: var(--primary);
  box-shadow: 0 0 0 3px var(--primary-bg);
}

.input-prefix,
.input-suffix {
  padding: var(--space-3);
  background: var(--bg-secondary);
  color: var(--text-muted);
  font-size: var(--text-sm);
  white-space: nowrap;
}

.input-prefix {
  border-right: 1px solid var(--border);
}

.input-suffix {
  border-left: 1px solid var(--border);
}

.input-group .input {
  border: none;
  flex: 1;
  background: transparent;
}

.input-group .input:focus {
  box-shadow: none;
}

.field-hint {
  font-size: var(--text-xs);
  color: var(--text-muted);
  line-height: 1.4;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
}

.radio-item {
  display: flex;
  align-items: flex-start;
  gap: var(--space-3);
  padding: var(--space-3);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  cursor: pointer;
  transition: all 0.2s ease;
}

.radio-item:hover {
  border-color: var(--primary);
  background: var(--primary-bg);
}

.radio-item input[type="radio"] {
  margin: 0;
  accent-color: var(--primary);
}

.radio-label {
  font-weight: 500;
  color: var(--text);
}

.radio-desc {
  font-size: var(--text-xs);
  color: var(--text-muted);
  margin-top: var(--space-1);
}

.switch-group {
  display: flex;
  align-items: center;
  gap: var(--space-3);
}

.switch {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  cursor: pointer;
}

.switch input[type="checkbox"] {
  display: none;
}

.switch-slider {
  width: 44px;
  height: 24px;
  background: var(--border);
  border-radius: 12px;
  position: relative;
  transition: background 0.2s ease;
}

.switch-slider::before {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  width: 20px;
  height: 20px;
  background: white;
  border-radius: 50%;
  transition: transform 0.2s ease;
}

.switch input[type="checkbox"]:checked + .switch-slider {
  background: var(--primary);
}

.switch input[type="checkbox"]:checked + .switch-slider::before {
  transform: translateX(20px);
}

.switch-label {
  font-size: var(--text-sm);
  font-weight: 500;
  color: var(--text);
}

.preview-section {
  grid-column: 1 / -1;
  padding: var(--space-6);
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
}

.coupon-preview {
  display: flex;
  justify-content: center;
  margin-top: var(--space-4);
}

.coupon-card {
  width: 300px;
  background: linear-gradient(135deg, var(--primary), var(--primary-600));
  border-radius: var(--radius-lg);
  padding: var(--space-6);
  color: white;
  box-shadow: var(--shadow-lg);
  position: relative;
  overflow: hidden;
}

.coupon-card.discount {
  background: linear-gradient(135deg, var(--info), var(--info-600));
}

.coupon-card::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  transform: rotate(45deg);
}

.coupon-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-4);
}

.coupon-value .value {
  font-size: var(--text-3xl);
  font-weight: 700;
}

.coupon-type {
  font-size: var(--text-xs);
  opacity: 0.8;
  text-transform: uppercase;
}

.coupon-body {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.coupon-name {
  font-size: var(--text-lg);
  font-weight: 600;
}

.coupon-condition,
.coupon-validity {
  font-size: var(--text-sm);
  opacity: 0.9;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--space-3);
  padding-top: var(--space-6);
  border-top: 1px solid var(--border);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: var(--space-2);
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
    gap: var(--space-6);
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .coupon-card {
    width: 100%;
    max-width: 280px;
  }
}
</style>